package com.duowan.cms.intf.util;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.duowan.cms.common.util.StringUtil;
import com.duowan.cms.common.webapp.property.ExtendedPropertyPlaceholderConfigurer.PropertiesHolder;

public class IPFilter {

    private static final Logger logger = Logger.getLogger(IPFilter.class);

    /**
     * 获取被授权的IP
     * @return
     */
    private static List<String> getAllowableIp(String ipConfigId) {
        List<String> ips = new ArrayList<String>();
        String users = PropertiesHolder.get(ipConfigId);
        if (users.length() > 0) {
            String[] ipArray = users.split(",|;");
            for(String ip : ipArray) {
                if(!StringUtil.isEmpty(ip)) {
                    ips.add(ip);
                }
            }
        }
        return ips;
    }


    public static boolean isLegalIp(String ip, String ipConfigId) {

        String[] ip_part = ip.split("\\.");
        if (ip_part.length != 4)
            return false;

        List<String> list = getAllowableIp(ipConfigId);

        if (list.contains("*"))
            return true;
        if (list.contains(ip))
            return true;
        String ip_pattern1 = ip_part[0] + "." + ip_part[1] + "." + ip_part[2] + ".*";
        String ip_pattern2 = ip_part[0] + "." + ip_part[1] + ".*.*";
        String ip_pattern3 = ip_part[0] + ".*.*.*";
        if (list.contains(ip_pattern1) || list.contains(ip_pattern2) || list.contains(ip_pattern3))
            return true;
        return false;
    }
    
    public static String getRealIp(HttpServletRequest req) {
        String ip = req.getHeader("X-Forwarded-For");
        if(StringUtil.isEmpty(ip)) {
            return req.getRemoteAddr();
        }
        ip = ip.split(", ")[0].trim();
        if("127.0.0.1".equals(ip)) {
            return req.getRemoteAddr();
        }
        return ip;
    }

    public static void main(String[] args) {
        
        final String CHANNELINFO_ALLOWEDIP = "ip_getChannelInfo";
        System.out.println(isLegalIp("127.a.f.asfas", CHANNELINFO_ALLOWEDIP));
        
        try {
            Thread.sleep(15 * 1000L);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(isLegalIp("127.a.f.asfas", CHANNELINFO_ALLOWEDIP));
    }
}
